package logic

import (
	"context"
	"encoding/json"
	"teatch/model/cache"
	"teatch/model/mysql"
	"teatch/teacherrpc/internal/svc"
	"teatch/teacherrpc/teacherrpc"
	"teatch/teacherrpc/teacherrpcclient"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type CollectListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCollectListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CollectListLogic {
	return &CollectListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 收藏列表
func (l *CollectListLogic) CollectList(in *teacherrpc.CollectListRequest) (*teacherrpc.CollectListResponse, error) {
	// todo: add your logic here and delete this line

	offset := (in.Page - 1) * in.Size

	var data []mysql.Collect
	 
	cacheList, _ := cache.Rdb.Get(l.ctx, "key").Result()
	if cacheList == "" {
		tx := mysql.DB.Offset(int(offset)).Limit(int(in.Size)).Order("created_at desc")
		tx.Find(&data)
		cachejson, _ := json.Marshal(data)
		cache.Rdb.Set(l.ctx, "key", cachejson, time.Minute*15)
	} else {
		json.Unmarshal([]byte(cacheList), &data)
	}

	var CollectList []*teacherrpcclient.CollectList

	for _, datum := range data {
		list := teacherrpc.CollectList{
			UserId:   int64(datum.UserId),
			CourseId: int64(datum.CourseId),
			Courses:  datum.Courses,
			Num:      int64(datum.Num),
		}

		CollectList = append(CollectList, &list)
	}

	return &teacherrpc.CollectListResponse{
		List: CollectList,
	}, nil
}
